package com.example.demo.config;

import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by void on 2020/4/12.
 */
@Configuration
public class WebConfig{

    /**
     * 可以通过request.getRemoteAddr()获取nginx代理下的请求真实ip地址
     * 但是需要nginx在location节点下配置
     *   proxy_set_header            Host $host;
         proxy_set_header            X-real-ip $remote_addr;
         proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
        最主要的是X-Forwarded-For 属性,源码里解析设置自己的remoteAddr属性,并且清空该header
        针对伪造的X-Forwarded-For 可以参考 https://segmentfault.com/a/1190000019197577 设置最外层代理为tcp实际客户端ip
     * @return
     */
    @Bean
    public RemoteIpFilter myRemoteIpFilter(){
        return new MyRemoteIpFilter();
    }

    @Bean
    public FilterRegistrationBean testFilterRegistration(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(myRemoteIpFilter());
        registrationBean.addUrlPatterns("/*");
        //TODO 此处配置不知何用
        registrationBean.addInitParameter("key1", "value1");
        registrationBean.setOrder(1);
        return registrationBean;
    }
}
